package Reaction::UI::ViewPort::Field;

use Reaction::Class;

class Field is 'Reaction::UI::ViewPort', which {

  has name => (
    isa => 'Str', is => 'rw', required => 1
  );
  
  has action => (
    isa => 'Reaction::InterfaceModel::Action',
    is => 'ro', required => 0, predicate => 'has_action',
  );
  
  has attribute => (
    isa => 'Reaction::Meta::InterfaceModel::Action::ParameterAttribute',
    is => 'ro', predicate => 'has_attribute',
  );
  
  has value => (
    is => 'rw', set_or_lazy_build('value'), trigger_adopt('value'),
    predicate => 'has_value', clearer => 'clear_value',
  );
  
  has needs_sync => (
    isa => 'Int', is => 'rw', default => 0
  );
  
  has label => (
    isa => 'Str', is => 'rw', set_or_lazy_build('label')
  );
  
  has message => (
    isa => 'Str', is => 'rw', required => 1, default => sub { '' }
  );
  
  implements BUILD => as {
    my ($self) = @_;
    if (!$self->has_attribute != !$self->has_action) { confess "Should have both action and attribute or neither"; }
  };
  
  implements build_label => as {
    my ($self) = @_;
    return join(' ', map { ucfirst } split('_', $self->name));
  };
  
  implements build_value => as {
    my ($self) = @_;
    if ($self->has_attribute) {
      my $reader = $self->attribute->reader;
      my $predicate = $self->attribute->predicate;
      if (!$predicate || $self->action->$predicate) {
        return $self->action->$reader;
      }
    }
    return '';
  };
  
  implements adopt_value => as {
    my ($self) = @_;
    $self->needs_sync(1) if $self->has_attribute;
  };
  
  implements sync_to_action => as {
    my ($self) = @_;
    return unless $self->needs_sync && $self->has_attribute && $self->has_value;
    my $attr = $self->attribute;
    my $value = $self->value;
    if (my $tc = $attr->type_constraint) {
      if ($tc->has_coercion) {
        $value = $tc->coercion->coerce($value);
      }
      my $error = $tc->validate($value);
      if (defined $error) {
        $self->message($error);
        return;
      }
    }
    my $writer = $attr->writer;
    confess "No writer for attribute" unless defined($writer);
    $self->action->$writer($value);
    $self->needs_sync(0);
  };
  
  implements sync_from_action => as {
    my ($self) = @_;
    return unless !$self->needs_sync && $self->has_attribute;
    $self->message($self->action->error_for($self->attribute)||'');
  };
  
  override accept_events => sub { ('value', super()) };

};

1;  
